#include <stdio.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

#include <string.h>
#include <errno.h>

// ./cp1 <file1> <file2> <file3> <file4>
int main(int argc, char const *argv[])
{
    if(argc < 3 || argc > 12) return -1;
    int read_fds[10];
    bzero(read_fds, 10); // 初始化

    for(int i=0;i<argc-2; i++){
        read_fds[i] = open(argv[i+1], O_RDONLY);
        if(read_fds[i] < 0){
            printf("%s open fail: %s\n", argv[i+1], strerror(errno));
            return -1;
        }
    }
    

    int fd2 = open(argv[argc-1], O_CREAT|O_WRONLY|O_TRUNC, 0644);
    
    int active_num; // 存储select()函数返回的结果, 选择读集和写集中的可用FD的数量
    fd_set read_set, write_set; 
    char buf[512] = ""; // 缓冲区

    int read_status;
    while(1){
        read_status = 0;
        // 清空Select的读集和写集
        FD_ZERO(&read_set);
        FD_ZERO(&write_set);

        // 将read_fds,fd2分别添加 到读集和写集中
        for(int i=0;i<argc-2;i++){
            if(read_fds[i] == -1) continue;
            FD_SET(read_fds[i], &read_set);
            read_status = 1; // 还有读任务
        }
        if(read_status == 0) break;  // 没有读任务了
        
        FD_SET(fd2, &write_set);

        // 选择可读或读写的FD
        active_num = select(fd2+1, &read_set, &write_set, NULL, NULL);
        if(active_num == -1){
            perror("select");
            break;
        }
        printf("active_fd is %d\n", active_num);

         for(int i=0;i<argc-2;i++){
            if(read_fds[i] == -1) continue;
            if(FD_ISSET(read_fds[i], &read_set)){
                ssize_t len = read(read_fds[i], buf, 512);  // 0,EOF(-1)
                if(len <= 0) { 
                    close(read_fds[i]);
                    read_fds[i] = -1;
                    break;
                }
            }
            if(FD_ISSET(fd2, &write_set)){
                 write(fd2, buf, strlen(buf));
                 bzero(buf, 512);
            }
        }
       

        
    }
    close(fd2);
    printf("OK\n");
    return 0;
}
